<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-18 19:28:34
 * @LastEditTime: 2023-02-16 18:35:13
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 新建、编辑楼宇
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="true"
    :maskClosable="true"
    :visible="visible"
    :width="$store.getters.isMobile ? 350 : 800"
    @close="handleClose"
    :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
    }"
  >
    <section class="content">
      <a-form layout="vertical">
        <a-tabs v-model:activeKey="activeTabKey" size="small">
          <a-tab-pane :key="TAB_KEYS[0]" tab="基础配置">
            <section class="form">
              <div class="text-title">基础信息</div>
              <a-row :gutter="16" class="mt-10">
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item v-bind="validateInfos.village_id">
                    <template #label>
                      <span>{{ $L("所属项目") }}</span>
                    </template>
                    <a-select
                      placeholder="请选择..."
                      v-model:value="modelRef.village_id"
                      :disabled="id == 0 ? false : true"
                    >
                      <a-select-option
                        :value="project.id"
                        :key="project.id"
                        v-for="project of projectList"
                      >
                        {{ project.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item v-bind="validateInfos.build_number">
                    <template #label>
                      <span>{{ $L("楼宇") }}编号</span>
                    </template>
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.build_number"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item v-bind="validateInfos.build_name">
                    <template #label>
                      <span>{{ $L("楼宇名称") }}</span>
                      <text-tip
                        :tips="`如果${BLCOMMON.utils.L(
                          '项目'
                        )}中有单元级别，您可以命名“1栋1单元”或者“1幢1单元”。系统在多层级展示时将会自动归类。`"
                      />
                    </template>
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.build_name"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 16">
                  <a-form-item label="所属地区" v-bind="validateInfos.area">
                    <a-cascader
                      v-model:value="modelRef.area"
                      :options="areaOptions"
                      :load-data="loadAreaData"
                      placeholder="请选择所属地区"
                      change-on-select
                      @change="areaSelectChange"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item v-bind="validateInfos.address">
                    <template #label>
                      <span>{{ $L("楼宇") }}地址</span>
                    </template>
                    <a-auto-complete
                      v-model:value="modelRef.address"
                      @search="onSearch"
                      @select="changeAddress"
                      :placeholder="placeholderAddress"
                      allowClear
                    >
                      <template #options>
                        <a-select-option
                          v-for="addres of addressOptions"
                          :key="addres"
                        >
                          <span>{{ addres.title }}</span
                          ><span style="color: #cfcfcf; padding-left: 5px">{{
                            addres.address
                          }}</span>
                        </a-select-option>
                      </template>
                    </a-auto-complete>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16" class="mt-10">
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="产权性质"
                    v-bind="validateInfos.property_right"
                  >
                    <a-select
                      placeholder="请选择..."
                      v-model:value="modelRef.property_right"
                    >
                      <a-select-option
                        :value="property.key"
                        :key="property.key"
                        v-for="property of propertyRightList"
                      >
                        {{ property.value }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="不动产证编号"
                    v-bind="validateInfos.estate_number"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.estate_number"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="产权编号"
                    v-bind="validateInfos.property_number"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.property_number"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16" class="mt-10">
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="土地编号"
                    v-bind="validateInfos.land_number"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.land_number"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item label="排序值">
                    <a-input-number
                      id="inputNumber"
                      style="width: 100%"
                      placeholder="排序值越大展示越靠前"
                      v-model:value="modelRef.sort"
                      :min="0"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <!-- <a-row :gutter="16" class="mt-10">
         
              </a-row> -->
              <div class="text-title">{{ $L("楼宇") }}面积</div>
              <a-row :gutter="16">
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="建筑面积"
                    v-bind="validateInfos.build_area"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.build_area"
                      suffix="㎡"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="产权面积"
                    v-bind="validateInfos.property_area"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.property_area"
                      suffix="㎡"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="可租面积"
                    v-bind="validateInfos.rentable_area"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.rentable_area"
                      suffix="㎡"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="自用面积"
                    v-bind="validateInfos.self_use_area"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.self_use_area"
                      suffix="㎡"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="配套面积"
                    v-bind="validateInfos.supporting_area"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.supporting_area"
                      suffix="㎡"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="车位面积"
                    v-bind="validateInfos.parking_area"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.parking_area"
                      suffix="㎡"
                    />
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                      label="车位数量"
                      v-bind="validateInfos.parking_count"
                  >
                    <a-input
                        placeholder="请输入..."
                        v-model:value="modelRef.parking_count"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="$store.getters.isMobile ? 24 : 8">
                  <a-form-item
                    label="标准层高"
                    v-bind="validateInfos.floor_height"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.floor_height"
                      suffix="m"
                    />
                  </a-form-item>
                </a-col> -->
              </a-row>
              <!-- <a-row :gutter="16">
                <a-col :span="8">
                  <a-form-item label="管理面积" v-bind="validateInfos.name">
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.name"
                      suffix="㎡"
                    />
                  </a-form-item>
                </a-col>
              </a-row> -->
              <!-- <div class="text-title">提醒设置</div>
              <a-row :gutter="16" class="mt-10">
                <a-col :span="8">
                  <a-form-item
                    label="合同提前提醒天数"
                    v-bind="validateInfos.name"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.name"
                      suffix="天"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item
                    label="账单提前提醒天数"
                    v-bind="validateInfos.name"
                  >
                    <a-input
                      placeholder="请输入..."
                      v-model:value="modelRef.name"
                      suffix="天"
                    />
                  </a-form-item>
                </a-col>
              </a-row> -->
              <div class="text-title">默认收支账户</div>
              <a-row :gutter="16" class="mt-10">
                <a-col :span="$store.getters.isMobile ? 24 : 14">
                  <a-form-item
                    label="选择账户"
                    v-bind="validateInfos.account_default"
                  >
                    <a-select
                      placeholder="请选择..."
                      v-model:value="modelRef.account_default"
                      allowClear
                    >
                      <a-select-option
                        :value="account.id"
                        :key="account.id"
                        v-for="account of accountList"
                      >
                        {{ account.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col
                  :span="$store.getters.isMobile ? 24 : 10"
                  class="text-right"
                >
                  <a-tooltip>
                    <template #title>
                      <span v-if="!id"
                        >如需新建收支账户，请在新建后编辑楼宇</span
                      >
                    </template>
                    <a-button
                      type="primary"
                      ghost
                      @click="addNewAccount"
                      :disabled="!id"
                    >
                      <template #icon>
                        <PlusOutlined />
                      </template>
                      新建账户
                    </a-button>
                  </a-tooltip>
                </a-col>
              </a-row>
              <a-row v-if="currentAccount">
                <a-descriptions
                  :column="$store.getters.isMobile ? 2 : 3"
                  layout="vertical"
                >
                  <a-descriptions-item label="收款公司">
                    {{ currentAccount.company }}
                  </a-descriptions-item>
                  <a-descriptions-item label="开户银行">
                    {{ currentAccount.bank }}
                  </a-descriptions-item>
                  <a-descriptions-item label="银行账号">
                    {{ currentAccount.bank_account }}
                  </a-descriptions-item>
                </a-descriptions>
              </a-row>
            </section>
          </a-tab-pane>
          <a-tab-pane :key="TAB_KEYS[1]" tab="拓展信息">
            <div class="text-title">拓展信息</div>
            <a-row :gutter="16" class="mt-10">
              <a-col :span="$store.getters.isMobile ? 24 : 14">
                <a-form-item>
                  <template #label>
                    <a-row justify="space-between" style="width: 100%">
                      <span>{{ $L("楼宇") }}标签</span>
                      <a-checkbox v-model:checked="is_hot"
                        >热门{{ $L("楼宇") }}
                      </a-checkbox>
                    </a-row>
                  </template>
                  <a-select
                    v-model:value="tag_info"
                    :options="tagOptions"
                    mode="multiple"
                    :placeholder="placeholderTag"
                  >
                    <template #dropdownRender="{ menuNode: menu }">
                      <v-nodes :vnodes="menu" />
                      <a-divider style="margin: 4px 0" />

                      <!--@mousedown="e => e.preventDefault()"  -->
                      <div
                        style="
                          padding: 4px 8px;
                          cursor: pointer;
                          color: #1890ff;
                          text-align: center;
                        "
                        @mousedown="(e) => e.preventDefault()"
                        @click="addTag"
                      >
                        <!-- <plus-outlined /> -->
                        添加
                      </div>
                    </template>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : 10">
                <a-form-item label="总楼层">
                  <a-input
                    placeholder="例：地上18层"
                    v-model:value="modelRef.extra_config.total_layer"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16" class="mt-10">
              <a-col :span="24">
                <a-form-item>
                  <template #label>
                    <span>图片</span>
                    <text-tip :tips="['建议上传4：3的图片']" :showNo="false" />
                  </template>
                  <a-upload
                    :action="$utils.imgAction"
                    :headers="{ 'org-token': $store.getters.token }"
                    :multiple="false"
                    v-model:file-list="fileList"
                    @change="handleUploadChange"
                    @remove="removeChange"
                    name="image"
                    :data="{ dir: 'org_village_building' }"
                    accept="image/jpg,image/jpeg,image/gif,image/png"
                    list-type="picture-card"
                  >
                    <div v-if="!fileList.length">
                      <PlusOutlined />
                      <div style="padding-top: 4px">上传</div>
                    </div>
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :span="23">
                <a-form-item>
                  <template #label>
                    <span>设施支持</span>
                    <text-tip
                      :tips="['用于移动端的招商展示']"
                      :showNo="false"
                    />
                  </template>
                  <a-checkbox-group
                    v-model:value="modelRef.extra_config.installation"
                    :options="plainOptions"
                  >
                  </a-checkbox-group>
                </a-form-item>
              </a-col>
              <a-col :span="23">
                <a-form-item>
                  <template #label>
                    <span>{{ $L("楼宇") }}介绍</span>
                  </template>
                  <vue-ueditor-wrap
                    v-model="modelRef.extra_config.info"
                    :config="ueditorEditorConfig"
                    editor-id="editor-demo-01"
                  ></vue-ueditor-wrap>
                </a-form-item>
              </a-col>
            </a-row>

            <a-tabs
              v-model:activeKey="currentVisualTab"
              @change="onVisualTabChange"
            >
              <a-tab-pane
                :key="item.key"
                :tab="item.tab"
                v-for="item of visualTabList"
              ></a-tab-pane>
            </a-tabs>
            <a-row class="mt-20">
              <a-col :span="24">
                <a-form-item>
                  <template v-if="currentVisualTab == '3d'">
                    <a-upload
                      v-model:file-list="file3dList"
                      name="file"
                      :multiple="false"
                      :action="$utils.fileAction"
                      :headers="{ 'org-token': $store.getters.token }"
                      :showUploadList="true"
                      @change="handle3dUploadChange"
                      accept=".doc"
                      :data="{ dir: 'org_village_fbx' }"
                    >
                      <a-button v-if="!file3dList.length">
                        <UploadOutlined />
                        点击上传
                      </a-button>
                    </a-upload>
                  </template>
                  <template v-if="currentVisualTab == 'visualPic'">
                    <a-upload
                      v-model:file-list="visualPicList"
                      name="file"
                      key="visualPicList"
                      :multiple="false"
                      :action="$utils.fileAction"
                      :headers="{ 'org-token': $store.getters.token }"
                      :showUploadList="true"
                      @change="handleVisualPicUpload"
                      accept="image/jpg,image/jpeg,image/png"
                      :data="{ dir: 'org_village' }"
                    >
                      <a-button v-if="!visualPicList.length">
                        <UploadOutlined />
                        点击上传
                      </a-button>
                    </a-upload>
                  </template>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane :key="TAB_KEYS[2]" tab="营收目标">
            <a-table
              :columns="revenueColumns"
              :data-source="revenueYearTargets"
              rowKey="year"
              :scroll="{
                x: 'max-content',
                y: $store.getters.isMobile ? 500 : undefined,
              }"
            >
              <template #title>
                <div class="text-right">
                  <a-button
                    type="primary"
                    @click="addRevenueTarget"
                    :disabled="addDisabled"
                  >
                    <template #icon>
                      <PlusOutlined />
                    </template>
                    添加目标
                  </a-button>
                </div>
              </template>
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'year'">
                  <a-select
                    v-if="record.editable"
                    style="width: 100%"
                    placeholder="请选择..."
                    v-model:value="targetYear"
                  >
                    <a-select-option
                      :value="year"
                      :key="year"
                      v-for="year of yearOptions"
                    >
                      {{ year }}
                    </a-select-option>
                  </a-select>
                  <span v-else>{{ text }}</span>
                </template>
                <template v-if="column.key === 'target'">
                  <a-input
                    v-if="record.editable"
                    v-model:value="targetRevenue"
                    suffix="万元"
                    placeholder="请输入..."
                  />
                  <span v-else>{{ text }}</span>
                </template>
                <template v-if="column.key === 'action'">
                  <template v-if="record.editable">
                    <a-button type="link" @click="handleTargetAddFinish"
                      >完成</a-button
                    >
                    <a-button type="link" @click="handleTargetAddCancel"
                      >取消</a-button
                    >
                  </template>
                  <a-button
                    v-else
                    type="link"
                    danger
                    @click="handleTargetAddDel(record)"
                    >删除</a-button
                  >
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </section>

    <div class="drawer-footer flex justify-between">
      <section>
        <a-button
          type="primary"
          class="mr-10"
          :disabled="lastDisabled"
          @click="changeTab('last')"
        >
          上一项
        </a-button>
        <a-button
          type="primary"
          :disabled="nextDisabled"
          @click="changeTab('next')"
        >
          下一项
        </a-button>
      </section>
      <section>
        <a-button class="mr-10" @click.prevent="handleClose">关闭</a-button>
        <a-button type="primary" @click.prevent="onSubmit">提交</a-button>
      </section>
    </div>
    <account-add
      :visible="addAccountVisible"
      @cancel="handleAddAccountClose"
      @success="handleAddAccountSuccess"
      @request="$utils.commonRequest"
    ></account-add>
    <!-- 添加租客标签 -->
    <EditTag
      @closeTag="editTagClose"
      @success="editSuccess"
      :visible="editVisible"
    ></EditTag>
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  watch,
  ref,
  reactive,
  toRaw,
  toRefs,
} from "vue";
import {
  PlusOutlined,
  FileTextOutlined,
  InboxOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue";
import moment from "moment";
import { Form, message } from "ant-design-vue";
import AccountAdd from "../../../setting/UserAccount/modules/AccountAdd.vue";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
// import actions from "../../../../common/utils/action";
import EditTag from "./EditTag.vue";
import BLCOMMON, { TextTip } from "bl-common-vue3";
import store from "../../../../store";
import { VueUeditorWrap } from "vue-ueditor-wrap";

const useForm = Form.useForm;

export default defineComponent({
  name: "BuildingEdit",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    villageId: {
      type: [String, Number],
      default: 0,
    },
  },
  components: {
    AccountAdd,
    PlusOutlined,
    EditTag,
    TextTip,
    FileTextOutlined,
    InboxOutlined,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes;
    },
    UploadOutlined,
    VueUeditorWrap
  },
  setup(props, context) {
    const state = reactive({
      visualTabList: [
        {
          key: "3d",
          tab: "3D模型",
        },
        {
          key: "visualPic",
          tab: "实景图",
        },
      ],
      currentVisualTab: "3d",
      visualPicList: [],

      ueditorEditorConfig: {
        UEDITOR_HOME_URL: utils.staticUeditorEditorPaths, // 访问 UEditor 静态资源的根路径，可参考常见问题1
        serverUrl: request.BASE_URL + "/public/system/uploadUEditor", // 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        initialFrameHeight: 350,
        autoHeightEnabled: false,
        enableAutoSave: false,
      },
    });
    // 标题
    const title = computed(() => {
      return props.id
        ? "编辑" + BLCOMMON.utils.L("楼宇")
        : "添加" + BLCOMMON.utils.L("楼宇");
    });

    // 当前选中tab
    const TAB_KEYS = reactive(["basic", "target"]);

    const activeTabKey = ref(TAB_KEYS[0]);

    const lastDisabled = ref(true);
    const nextDisabled = ref(false);
    let tabIndex = 0;
    watch(activeTabKey, (val) => {
      tabIndex = TAB_KEYS.findIndex((item) => item === val);
      lastDisabled.value = tabIndex < 1;
      nextDisabled.value = tabIndex === TAB_KEYS.length - 1;
    });
    const changeTab = (type) => {
      type === "last"
        ? (activeTabKey.value = TAB_KEYS[tabIndex - 1])
        : (activeTabKey.value = TAB_KEYS[tabIndex + 1]);
    };
    const tag_info = ref([]);
    // 表单
    const modelRef = reactive({
      village_id: undefined,
      build_number: "",
      build_name: "",
      address: "",
      floor_height: "",
      property_right: "owner",
      build_area: "",
      property_area: "",
      rentable_area: "",
      self_use_area: "",
      supporting_area: "",
      property_number: "",
      land_number: "",
      estate_number: "",
      parking_area: "",
      parking_count: "",
      revenue_target: [],
      account_default: undefined,
      sort: "",

      extra_config: {
        installation: [],
        info: "",
      },
      area: [], //所属地区
      three_dimensional_file: "",
    });
    const numberRule = [
      {
        validator: (rules, value) => utils.numberValidator(rules, value),
        trigger: "change",
      },
    ];
    const rulesRef = reactive({
      village_id: [{ required: true, message: "必选项" }],
      build_name: [{ required: true, message: "必填项" }],
      property_right: [{ required: true, message: "必选项" }],
      build_area: [
        {
          required: true,
          validator: (rules, value) => utils.numberValidator(rules, value),
          trigger: "change",
        },
      ],
      property_area: [
        {
          required: true,
          validator: (rules, value) => utils.numberValidator(rules, value),
          trigger: "change",
        },
      ],
      rentable_area: numberRule,
      self_use_area: numberRule,
      supporting_area: numberRule,
      parking_area: numberRule,
      parking_count: numberRule,
      floor_height: numberRule,
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    // 营收目标
    const revenueYearTargets = ref([]);
    let addDisabled = ref(false);
    const addRevenueTarget = () => {
      addDisabled.value = true;
      revenueYearTargets.value.push({
        year: "",
        target: "",
        editable: true,
      });
    };
    const nowYear = moment().year();
    let yearOptions = [];
    for (let i = 0; i < 20; i++) {
      yearOptions.push(nowYear + i);
    }
    const targetYear = ref(nowYear);
    const targetRevenue = ref("");
    const handleTargetAddFinish = () => {
      if (!targetRevenue.value || !targetYear.value) {
        message.warning("请填写年份和营收目标~");
        return;
      }
      if (!utils.numberReg.test(targetRevenue.value)) {
        message.warning("营收目标只能填写数字哦~");
        return;
      }
      const index = revenueYearTargets.value.findIndex(
        (item) => item.year == targetYear.value
      );
      if (index > -1) {
        message.warning(`${targetYear.value}年份的营收目标您已经添加过了哦~`);
        return;
      }
      revenueYearTargets.value[revenueYearTargets.value.length - 1] = {
        year: targetYear.value,
        target: targetRevenue.value,
      };
      resetTargetValue();
    };
    const handleTargetAddCancel = () => {
      revenueYearTargets.value.splice(revenueYearTargets.value.length - 1, 1);
      resetTargetValue();
    };
    const handleTargetAddDel = (record) => {
      const index = revenueYearTargets.value.findIndex(
        (item) => item.year == record.year
      );
      revenueYearTargets.value.splice(index, 1);
    };
    const resetTargetValue = () => {
      targetYear.value = nowYear;
      targetRevenue.value = "";
      addDisabled.value = false;
    };

    // 收支账户
    const accountList = ref([]);
    const getAccountList = () => {
      request.get("/org", "/manage/account/all").then((res) => {
        accountList.value = res.list;
        if (res.list.length && modelRef.account_default == undefined) {
          modelRef.account_default = res.list[0].id;
        }
      });
    };
    const currentAccount = computed(() => {
      let account = null;
      if (modelRef.account_default) {
        account = accountList.value.find(
          (item) => item.id == modelRef.account_default
        );
      }
      return account;
    });
    // 新增收支账户
    const addAccountVisible = ref(false);
    const addNewAccount = () => {
      addAccountVisible.value = true;
    };
    const handleAddAccountClose = () => {
      addAccountVisible.value = false;
    };
    const handleAddAccountSuccess = () => {
      getAccountList();
      handleAddAccountClose();
    };

    const projectList = ref([]);
    const getProjectList = () => {
      request
        .get("/org", "/build/villageAndBuildList", { show_by_type: 0 })
        .then((res) => {
          projectList.value = res.villageList;
          if (res.villageList.length && modelRef.village_id == undefined) {
            modelRef.village_id = props.villageId || res.villageList[0].id;
          }
        });
    };

    // 获取详情
    const detail = ref({});
    const getDetail = () => {
      if (!props.id) {
        return;
      }
      request
        .get("/village", "/project/build/get", {
          id: props.id,
          village_id: props.villageId,
        })
        .then((res) => {
          const { detail } = res;
          modelRef.extra_config.installation = detail.extra_config
            ? detail.extra_config.installation
            : [];

          setModelRef(detail);
          district_txt_list.value = detail.district_txt;
          is_hot.value = detail.is_hot == 0 ? false : true;
          lng = detail.lng;
          lat = detail.lat;
          if (detail.logo) {
            images = detail.logo;
            fileList.value = [
              {
                uid: "1",
                name: detail.logo,
                status: "done",
                url: detail.logo,
              },
            ];
          }

          modelRef.village_id = detail.village_id;
          modelRef.account_default = detail.account_default;
          revenueYearTargets.value = detail.revenue_target;
          tag_info.value = detail.tag_info || [];
          if (detail.three_dimensional_file) {
            file3dList.value = [
              {
                uid: "1",
                name: `${modelRef.build_name}_3D可视化模型.fbx`,
                status: "done",
                url: detail.three_dimensional_file,
              },
            ];
            state.visualTabList[0].tab = "3D模型(已上传)";
          }

          if (detail.dimensional_bg_img) {
            state.visualPicList = [
              {
                uid: "2",
                name: detail.dimensional_bg_img,
                status: "done",
                url: detail.dimensional_bg_img,
              },
            ];

            state.visualTabList[1].tab = "实景图(已上传)";
          }

          const { province_id, city_id, district_id, street_id, community_id } =
            detail;
          if (province_id) {
            modelRef.area.push(province_id);
            utils.getAreaOptions(1).then((list) => {
              areaOptions.value = list;
              let index = list.findIndex((item) => item.value == province_id);
              if (city_id && index > -1) {
                modelRef.area.push(city_id);
                let province = areaOptions.value[index];
                utils
                  .getAreaOptions(2, { id: province_id })
                  .then((cityList) => {
                    if (cityList.length) {
                      province.children = cityList;
                      index = cityList.findIndex(
                        (item) => item.value == city_id
                      );
                      if (district_id && index > -1) {
                        modelRef.area.push(district_id);
                        let city = province.children[index];
                        target.value = city.label;
                        utils
                          .getAreaOptions(3, { id: city_id })
                          .then((districtList) => {
                            if (districtList.length) {
                              city.children = districtList;
                              index = districtList.findIndex(
                                (item) => item.value == district_id
                              );
                              if (street_id && index > -1) {
                                modelRef.area.push(street_id);
                                let district = city.children[index];
                                utils
                                  .getAreaOptions(4, { id: district_id })
                                  .then((streetList) => {
                                    if (streetList.length) {
                                      district.children = streetList;
                                      index = streetList.findIndex(
                                        (item) => item.value == street_id
                                      );
                                      if (community_id && index > -1) {
                                        modelRef.area.push(community_id);
                                        let street = district.children[index];
                                        utils
                                          .getAreaOptions(5, { id: street_id })
                                          .then((communityList) => {
                                            if (communityList.length) {
                                              street.children = communityList;
                                            } else {
                                              street.isLeaf = true;
                                            }
                                          });
                                      }
                                    } else {
                                      district.isLeaf = true;
                                    }
                                  });
                              }
                            } else {
                              city.isLeaf = true;
                            }
                          });
                      }
                    } else {
                      province.isLeaf = true;
                    }
                  });
              }
            });
          }
        });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        if (modelRef[key] != undefined) {
          modelRef[key] = state[key];
        }
      }
    };

    const handleClose = () => {
      context.emit("cancel");
      add.value = 0;
      tag_info.value = [];
    };

    const is_hot = ref(false);
    const onSubmit = () => {
      add.value = 0;
      validate().then(() => {
        if (addDisabled.value) {
          handleTargetAddCancel();
        }
        let params = { ...toRaw(modelRef), needMsg: true };
        params.revenue_target = revenueYearTargets.value;
        // console.log("-----params", params);
        const success = (res) => {
          if (!props.id) {
            message.success("楼宇添加成功，需要在左上角选择楼宇哦~");
            store.dispatch("SetBuildingVisible", true);
          } else {
            message.success(res.msg || "保存成功！");
            tag_info.value = [];
          }
          context.emit("success");
        };
        params.lng = lng;
        params.lat = lat;
        params.district_txt = district_txt_list.value;
        params.province_id = params.area[0];
        params.city_id = params.area[1];
        params.district_id = params.area[2];
        params.street_id = params.area[3];
        params.community_id = params.area[4];
        delete params.area;

        params.tag_info = tag_info.value;
        params.is_hot = is_hot.value == false ? 0 : 1;
        params.logo = images;
        if (file3dList.value.length > 0) {
          params.three_dimensional_file = file3dList.value[0].url;
        } else {
          params.three_dimensional_file = "";
        }
        if (state.visualPicList.length > 0) {
          params.dimensional_bg_img = state.visualPicList[0].url;
        } else {
          params.dimensional_bg_img = "";
        }
        if (props.id) {
          params.id = props.id;
          request
            .put("/village", "/project/build", params)
            .then((res) => success(res));
        } else {
          request
            .post("/village", "/project/build", params)
            .then((res) => success(res));
        }
      });
    };

    // 租客标签
    const tagOptions = ref([]);

    // 添加租客标签
    const editVisible = ref(false);
    const addTag = () => {
      console.log("添加");
      editVisible.value = true;
    };
    const editTagClose = () => {
      editVisible.value = false;
    };
    const add = ref(0);
    const editSuccess = () => {
      editTagClose();
      tagList();
      add.value = 1;
    };
    const tagList = () => {
      request.get("/org", "/manage/taglib/build").then((res) => {
        if (props.id) {
          tagOptions.value = res.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
              id: item.id,
            };
          });
          if (add.value == 1) {
            tag_info.value.push(res.list[0].id);
          }
          return;
        }
        if (add.value == 1) {
          tag_info.value.push(res.list[0].id);
        }
        tagOptions.value = res.list.map((item) => {
          return {
            value: item.id,
            label: item.name,
            id: item.id,
          };
        });
      });
    };

    const file3dList = ref([]);
    const handle3dUploadChange = (info) => {
      let resFileList = [...info.fileList];
      resFileList = resFileList.slice(-1);
      file3dList.value = resFileList;
      const result = file3dList.value[0];
      if (result && result.response) {
        if (result.response.code == 1000) {
          modelRef.three_dimensional_file = result.response.data.fileUrl;
        } else {
          message.warning(result.response.msg);
        }
      }
    };
    // 图片上传
    const fileList = ref([]);
    let images = "";
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              images = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        images = "";
      }
      fileList.value = resFileList;
    };
    const removeChange = () => {
      fileList.value = [];
      images = "";
    };

    // 设施支持
    const plainOptions = ref([]);
    const installationLsit = () => {
      request.get("/village", "/project/build/installations").then((res) => {
        let arr = [];
        for (let i in res.list) {
          let o = {};
          o[i] = res.list[i];
          arr.push(o);
        }
        plainOptions.value = arr.map((item) => {
          return {
            label: Object.values(item),
            value: Object.keys(item).join(""),
          };
        });
      });
    };

    // 楼宇地址
    let target = ref("");
    let lat = null;
    let lng = null;
    const onSearch = (value) => {
      if (!value) {
        return;
      }
      getResult(
        value,
        target.value,
        (result) => (addressOptions.value = result)
      );
    };
    const changeAddress = (value) => {
      modelRef.address = value.title;
      lat = value.location.lat;
      lng = value.location.lng;
    };
    // 节流
    let timeout = null;
    let currentValue = "";
    //  节流
    const getResult = (value, target, callback) => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      currentValue = value;
      // 搜素请求
      const searchList = () => {
        request
          .get("/village", "/map/get/place", { city: target, keywords: value })
          .then((res) => {
            if (currentValue === value) {
              let result = [];
              if (res.list) {
                result = res.list;
              }
              callback(result);
            }
          });
      };
      timeout = setTimeout(searchList, 800);
    };
    const addressOptions = ref([]);

    // 城市选择
    const areaOptions = ref([]);
    let areas = {
      provinceId: "",
      provinceName: "",
      cityId: "",
      cityName: "",
      districtId: "",
      districtName: "",
      streetId: "",
      streetName: "",
    };
    const getArea = () => {
      utils.getAreaOptions(1).then((list) => {
        areaOptions.value = list;
      });
    };
    const district_txt_list = ref("");
    const areaChange = (areaChangeValue, value) => {
      areas.provinceId = value[0].value;
      areas.provinceName = value[0].label;
      areas.cityId = value[1].value;
      areas.cityName = value[1].label;
      areas.districtId = value[2].value;
      areas.districtName = value[2].label;
      areas.streetId = value[3].value;
      areas.streetName = value[3].label;
    };
    const areaSelectChange = (value, selectedOptions) => {
      let areaTxtArr = selectedOptions.map((item) => item.label);
      district_txt_list.value = areaTxtArr.join(",");
    };
    // 动态加载省市区信息
    const loadAreaData = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      if (targetOption.level == 2) {
        target.value = targetOption.label;
      }
      utils
        .getAreaOptions(targetOption.level + 1, {
          id: targetOption.value,
        })
        .then((res) => {
          if (res.length) {
            targetOption.children = res;
          } else {
            targetOption.isLeaf = true;
          }
          targetOption.loading = false;
        });
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
          tagList();
          installationLsit();
          getArea();
        } else {
          resetFields();
          detail.value = {};
          file3dList.value = [];
          revenueYearTargets.value = [];
          activeTabKey.value = TAB_KEYS[0];
          is_hot.value = false;
          fileList.value = [];
          images = "";
          lat = null;
          lng = null;
          state.visualPicList = [];
          state.currentVisualTab = "3d";
        }
      }
    );

    const init = () => {
      getDetail();
      getAccountList();
      getProjectList();
    };

    const onVisualTabChange = (key) => {
      state.currentVisualTab = key;
    };

    const handleVisualPicUpload = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              state.visualPicList = resFileList;
            } else {
              message.warning(file.response.msg);
            }
          }
        });
      }
    };

    return {
      title,
      TAB_KEYS,
      activeTabKey,
      lastDisabled,
      nextDisabled,
      modelRef,
      validateInfos,
      revenueColumns,
      revenueYearTargets,
      yearOptions,
      targetYear,
      targetRevenue,
      addDisabled,
      accountList,
      currentAccount,
      projectList,
      propertyRightList,
      addAccountVisible,
      file3dList,
      addRevenueTarget,
      handleTargetAddFinish,
      handleTargetAddCancel,
      handleTargetAddDel,
      changeTab,
      handleClose,
      onSubmit,
      handleAddAccountClose,
      handleAddAccountSuccess,
      addNewAccount,
      tagOptions,
      addTag,
      removeChange,
      editVisible,
      editTagClose,
      editSuccess,
      tag_info,
      is_hot,
      fileList,
      handle3dUploadChange,
      plainOptions,
      areaOptions,
      loadAreaData,
      areaChange,
      areaSelectChange,
      onSearch,
      addressOptions,
      changeAddress,
      handleUploadChange,
      detail,

      placeholderAddress: `请选择${BLCOMMON.utils.L("楼宇")}地址`,
      placeholderTag: `请选择${BLCOMMON.utils.L("楼宇")}地址`,
      placeholderExtra: `请输入${BLCOMMON.utils.L(
        "楼宇"
      )}简介，以在移动端进行更好的展示`,

      ...toRefs(state),
      onVisualTabChange,
      handleVisualPicUpload,
      BLCOMMON,
    };
  },
});

const revenueColumns = [
  {
    title: "年份",
    dataIndex: "year",
    key: "year",
    width: 120,
  },
  {
    title: "营收目标（万元）",
    dataIndex: "target",
    key: "target",
    width: 220,
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    fixed: "right",
    width: 140,
  },
];

const propertyRightList = [
  { key: "owner", value: "自持" },
  { key: "tenant", value: "承租" },
  { key: "ownerAndTenant", value: "自持 + 承租" },
  { key: "govFree", value: "政府免费使用" },
];
</script>
<style lang="less" scoped>
.content {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  :deep(.ant-form-vertical .ant-form-item-label > label) {
    width: 100%;
  }
}
:deep(
    .ant-table-bordered .ant-table-thead > tr > th,
    .ant-table-bordered .ant-table-tbody > tr > td
  ) {
  width: 236px;
}
:deep(.ant-checkbox-group-item + .ant-checkbox-group-item) {
  // margin: 5px 3px;
  // padding: 5px 2px;
  padding-bottom: 8px;
}
</style>
